package com.ip.student.util;

import com.ip.db.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Token工具类，用于实现单设备登录
 */
@Component
public class TokenUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);
    
    @Autowired
    private RedisUtil redisUtil;
    
    private static final String USER_TOKEN_PREFIX = "user_token:";
    
    /**
     * 保存用户token，实现单设备登录
     * @param username 用户名
     * @param token JWT token
     */
    public void saveUserToken(String username, String token) {
        logger.info("Saving token for user: {}", username);
        // 先删除旧的token
        String oldToken = (String) redisUtil.get(USER_TOKEN_PREFIX + username);
        logger.info("Old token for user {}: {}", username, oldToken);
        if (oldToken != null) {
            logger.info("Removing old token for user: {}", username);
            redisUtil.del("jwt_token:" + oldToken);
        }
        
        // 保存新的token关联
        redisUtil.set(USER_TOKEN_PREFIX + username, token);
        redisUtil.set("jwt_token:" + token, username);
        logger.info("Saved new token for user: {}, token: {}", username, token);
    }
    
    /**
     * 验证token是否有效
     * @param username 用户名
     * @param token JWT token
     * @return 是否有效
     */
    public boolean validateUserToken(String username, String token) {
        String savedToken = (String) redisUtil.get(USER_TOKEN_PREFIX + username);
        String savedUsername = (String) redisUtil.get("jwt_token:" + token);
        logger.info("Checking token validation - Username: {}, Token: {}", username, token);
        logger.info("Saved token for user {}: {}", username, savedToken);
        logger.info("Saved username for token: {}", savedUsername);
        boolean isValid = token.equals(savedToken) && username.equals(savedUsername);
        logger.info("Validating token for user: {}, token valid: {}, username valid: {}", username, token.equals(savedToken), username.equals(savedUsername));
        return isValid;
    }
    
    /**
     * 删除用户token
     * @param username 用户名
     */
    public void removeUserToken(String username) {
        String token = (String) redisUtil.get(USER_TOKEN_PREFIX + username);
        if (token != null) {
            redisUtil.del("jwt_token:" + token);
            redisUtil.del(USER_TOKEN_PREFIX + username);
            logger.info("Removed token for user: {}", username);
        }
    }
}